package cn.wolfcode.shop.web.resolver;

import cn.wolfcode.shop.anno.UserParam;
import cn.wolfcode.shop.domain.User;
import cn.wolfcode.shop.util.CookieUtils;
import cn.wolfcode.shop.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户参数解析器
 */
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 参数解析的条件
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return User.class.equals(methodParameter.getParameterType()) &&
                methodParameter.hasParameterAnnotation(UserParam.class);
    }

    // 解析逻辑
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //拿到请求中的token
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);// 指定类型转成 HttpServletRequest 类型的请求
        if (request == null) {
            return null;
        }

        String token = CookieUtils.getCookieValue(request, CookieUtils.USERTOKEN_NAME);
        if (StringUtils.isEmpty(token)) {
            return null;
        }

        String userJson = redisTemplate.opsForValue().get(RedisKeys.USER_LOGIN_TOKEN.join(token));
        if (StringUtils.isEmpty(userJson)) {
            return null;
        }
        return JSON.parseObject(userJson, User.class);
    }
}
